package com.esun.cheetah.view.personal;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.attention.AttenTeam;
import com.esun.cheetah.biz.personal.attention.AttentionListManager;
import com.esun.cheetah.biz.personal.attention.AttentionMatchDoneListCommunicater;
import com.esun.cheetah.biz.personal.attention.AttentionMatchFutureListCommunicater;
import com.esun.cheetah.biz.personal.attention.AttentionMatchRightNowListCommunicater;
import com.esun.cheetah.biz.personal.attention.LoginOutComm;
import com.esun.cheetah.biz.personal.attention.TouzhuMatchDoneListCommunicater;
import com.esun.cheetah.biz.personal.attention.TouzhuMatchFutureListCommunicater;
import com.esun.cheetah.biz.personal.attention.TouzhuMatchRightNowListCommunicater;
import com.esun.cheetah.biz.personal.personalcommunicater.CheckCardCommunicater;
import com.esun.cheetah.biz.personal.personalcommunicater.LoggedinrefreshCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.IntentKey;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.model.personal.attention.AttenTeamInfoChild;
import com.esun.cheetah.model.personal.attention.AttenTeamParent;
import com.esun.cheetah.model.personal.attention.AttentionGameInfo;
import com.esun.cheetah.model.personal.attention.AttentionGroupInfo;
import com.esun.cheetah.model.personal.attention.AttentionGroupInfo.GroupState;
import com.esun.cheetah.model.personal.attention.MatchInfo;
import com.esun.cheetah.view.HomeAct;
import com.esun.cheetah.view.custom.PullToRefreshExpandableListView;
import com.esun.cheetah.view.custom.PullToRefreshExpandableListView.OnRefreshListener;
import com.esun.cheetah.view.match.matchinfo.MatchInfoAct;
import com.esun.cheetah.view.personal.adapter.AbsAttentionAdapter;
import com.esun.cheetah.view.personal.adapter.AttentionMatchListAdapter;
import com.esun.cheetah.view.personal.adapter.EListAdapter;
import com.esun.cheetah.view.personal.adapter.EListAdapter.OnRecordCountListener;
import com.esun.cheetah.view.personal.adapter.TouzhuMatchListAdapter;
import com.esun.cheetah.view.personal.bindphone.BindPhoneActivity;
import com.esun.cheetah.view.personal.bindphone.ChangePhoneNumberActivity;
import com.esun.cheetah.view.personal.lotteryrecord.LotteryRecordAgp;
import com.esun.cheetah.view.personal.recharg.RechargeMenuPage;
import com.esun.cheetah.view.setting.service.NotificationService;
import com.esun.util.LoginTimeControl;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * 
 * @Package com.esun.cheetah.view.personal.LoggedinAct
 * @ClassName: LoggedinAct
 * @Description: TODO(logged activity)
 * @author handy <br/>
 * @date create at 2012-7-31 下午2:43:52
 * 
 */
public class LoggedinAct extends Activity implements OnClickListener {
	/** 比赛 */
	private RadioButton rbMatch;
	/** 球队 */
	private RadioButton rbTeam;
	/** 已投注记录 */
	private RadioButton rbAlreadyBettinGame;
	/** 添加球队button */
	private Button btAddteam;
	/** 控制列表的展开 */
	private int sign = -1;
	private Button btn_logout_in;
	private Button btn_refresh;
	private Button btn_betting_record_in;
	private Button btn_change_password_in;
	private Button btn_recharge_in;
	private Button btn_withdraw_deposit_in;
	private Button btn_bingding_bank_card_in;
	private Button btn_bingding_mobile_phone_in;
	private Button btnChangePhoneNumber;
	@SuppressWarnings("unused")
	private LoginTimeControl loginTimeControl_in;
	private TextView tv_return_username_in;
	private TextView tv_return_money_in;
	private TextView tv_bindmobile;

	@SuppressWarnings("unused")
	private Intent intentToSportteryFootball;
	@SuppressWarnings("unused")
	private Bundle bundleToSportteryFootbal;
	/** 用户关注球对childlist */
	@SuppressWarnings("unused")
	private List<AttenTeamInfoChild> attenTeamList;
	/** 关注球队 投注比赛的ListView */
	private PullToRefreshExpandableListView elistView;

	private Handler check_card_handler;
	private Handler refreshHandler;
	private Handler check_card_handler_withdrawal;
	private CheckCardCommunicater checkcardcommunicater;
	private LoggedinrefreshCommunicater loggedinrefreshCommunicater;
	private String userName;

	private SharedPreferences sharedPreferences_in;
	private ProgressDialog progressDialog;
	private Dialog quitDialog;
	private Button btnDialogSubmit;
	private Button btnDialogcancel;
	@SuppressWarnings("unused")
	private TextView tvDialogMsg;

	/**
	 * 已关注比赛列表、已投注比赛列表的Handler
	 */
	private AttentionHandler mHandler = new AttentionHandler();

	/**
	 * 关注比赛列表和已投注比赛列表
	 */
	private PullToRefreshExpandableListView attentionMatchList;
	// private PullToRefreshExpandableListView attentionTeamList;
	private PullToRefreshExpandableListView touzhuMatchList;
	private RelativeLayout attentionTeamLayout;

	private AttenTeam mAttenTeam;
	private boolean attenTeamIsFirstCall = true;
	/**
	 * 关注比赛列表的3个通信接口
	 */
	private AttentionMatchDoneListCommunicater mAttentionMatchDoneListCommunicater;
	private AttentionMatchFutureListCommunicater mAttentionMatchFutureListCommunicater;
	private AttentionMatchRightNowListCommunicater mAttentionMatchRightNowListCommunicater;

	/**
	 * 已投注比赛列表的3个通信接口
	 */
	private TouzhuMatchRightNowListCommunicater mTouzhuMatchRightNowListCommunicater;
	private TouzhuMatchFutureListCommunicater mTouzhuMatchFutureListCommunicater;
	private TouzhuMatchDoneListCommunicater mTouzhuMatchDoneListCommunicater;

	/**
	 * 关注比赛列表的数据适配器
	 */
	private AttentionMatchListAdapter mAttentionMatchListAdapter;

	/**
	 * 投注比赛列表的数据适配器
	 */
	private TouzhuMatchListAdapter mTouzhuMatchListAdapter;

	/**
	 * 标识关注比赛列表和投注比赛列表是否正在下拉刷新状态
	 */
	private boolean pullRefreshingAttention;
	private boolean pullRefreshingTouzhu;

	/**
	 * 已初始化了的关注列表在下拉刷新时会更新，这个用来统计刷新了几个二级列表
	 */
	private int mAttentionRefreshCount = 0;

	/**
	 * 同上
	 */
	private int mTouzhuRefreshCount = 0;

	/** 获得关注比赛handler */
	Handler gainAttenGameHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};

	/** 获得关注球队handler */
	Handler gainAtteTeamHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				mEListAdapter.update(mAttenTeam.getLlTeamR(),
						mAttenTeam.getAttenTeamInfoPa());
				mEListAdapter.notifyDataSetChanged();

				break;
			default:
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				tvTeamRecordEmptyHint.setVisibility(View.VISIBLE);
			}
			elistView.onRefreshComplete();
		}
	};

	/** 注销handler */
	Handler loginOutHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			case Config.COMMUNICATER_FAIL:
				break;
			case Config.COMMUNICATER_EXCEPTION:
				break;
			}
		}
	};

	private EListAdapter mEListAdapter;
	private TextView tvTeamRecordEmptyHint;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loggedin);
		loginTimeControl_in = new LoginTimeControl();
		initView();
		initListener();
		initHandler();
		initCommunicater();

		progressDialog = ViewerUtil.showProgressDialog(getParent(),
				Language.MSG_LOADING);
	}

	private void initView() {
		tvTeamRecordEmptyHint = (TextView) findViewById(R.id.tv_attention_team_empty);
		attentionTeamLayout = (RelativeLayout) findViewById(R.id.epl_attention_team_layout);
		elistView = (PullToRefreshExpandableListView) findViewById(R.id.exListView);
		mEListAdapter = new EListAdapter(this, elistView);
		elistView.setAdapter(mEListAdapter);
		elistView.setOnRefreshListener(new AttentionTeamOnRefreshListener());
		elistView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				AttenTeamParent group = mEListAdapter.getGroup(groupPosition);
				AttenTeamInfoChild info = mEListAdapter.getChild(groupPosition,
						childPosition);
				Intent intent = new Intent(LoggedinAct.this, EventDetails.class);
				Bundle bundle = new Bundle();
				bundle.putString(Config.TEAM_NAME, info.getTeam());
				bundle.putString(Config.TEAM_ID, info.getTeamid());
				bundle.putString(Config.TEAM_LEAGUE, group.getLeague());
				intent.putExtras(bundle);
				startActivity(intent);
				return true;
			}

		});

		elistView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				if (sign == -1) {
					elistView.expandGroup(groupPosition);
					elistView.setSelectedGroup(groupPosition);
					sign = groupPosition;
				} else if (sign == groupPosition) {
					elistView.collapseGroup(sign);
					sign = -1;
				} else {
					elistView.collapseGroup(sign);
					elistView.expandGroup(groupPosition);
					elistView.setSelectedGroup(groupPosition);
					sign = groupPosition;
				}
				return true;
			}
		});
		mEListAdapter.setOnRecordCountListener(new OnRecordCountListener() {

			@Override
			public void onEmpty() {
				tvTeamRecordEmptyHint.setVisibility(View.VISIBLE);

			}

			@Override
			public void onNotEmpty() {
				tvTeamRecordEmptyHint.setVisibility(View.INVISIBLE);

			}

		});

		userName = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE).getString(Key.KEY_USERNAME, "");
		// rlyNoTeam=(RelativeLayout) findViewById(R.id.rlyNoTeam);
		btAddteam = (Button) findViewById(R.id.btnAddAttenTeam);
		btAddteam.setOnClickListener(this);
		rbMatch = (RadioButton) findViewById(R.id.rbAttenMatch);
		rbMatch.setOnClickListener(this);
		rbTeam = (RadioButton) findViewById(R.id.rbAttenTeam);
		rbTeam.setOnClickListener(this);
		rbAlreadyBettinGame = (RadioButton) findViewById(R.id.rbAlreadyBettingGame);
		rbAlreadyBettinGame.setOnClickListener(this);
		btn_logout_in = (Button) findViewById(R.id.btn_logout);
		btn_logout_in.setOnClickListener(this);
		btn_refresh = (Button) findViewById(R.id.btn_refresh);
		btn_refresh.setOnClickListener(this);
		btn_betting_record_in = (Button) findViewById(R.id.btn_betting_record);
		btn_change_password_in = (Button) findViewById(R.id.btn_change_password);
		btn_recharge_in = (Button) findViewById(R.id.btn_recharge);
		btn_withdraw_deposit_in = (Button) findViewById(R.id.btn_withdraw_deposit);
		btn_bingding_bank_card_in = (Button) findViewById(R.id.btn_bingding_bank_card);
		btn_bingding_mobile_phone_in = (Button) findViewById(R.id.btn_bingding_mobile_phone);
		btnChangePhoneNumber = (Button) findViewById(R.id.btn_change_mobile_phone);
		tv_bindmobile = (TextView) findViewById(R.id.unbinding);
		tv_return_username_in = (TextView) findViewById(R.id.return_username);
		tv_return_money_in = (TextView) findViewById(R.id.return_money);

		btn_bingding_mobile_phone_in.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(LoggedinAct.this,
						BindPhoneActivity.class);
				startActivity(intent);
			}
		});

		btnChangePhoneNumber.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoggedinAct.this,
						ChangePhoneNumberActivity.class);
				startActivity(intent);

			}
		});

		// 关注列表的初始化
		attentionMatchList = (PullToRefreshExpandableListView) findViewById(R.id.epl_attention_match_list);
		mAttentionMatchListAdapter = new AttentionMatchListAdapter(this);
		attentionMatchList.setAdapter(mAttentionMatchListAdapter);
		attentionMatchList
				.setOnRefreshListener(new AttentionOnRefreshListener());
		attentionMatchList
				.setOnGroupExpandListener(new AttentionOnExpandListener());
		attentionMatchList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				if (mAttentionMatchListAdapter.getGroup(groupPosition)
						.getState() == GroupState.normal) {
					getToMatchDetailActivity(mAttentionMatchListAdapter
							.getChild(groupPosition, childPosition));
				}
				return true;
			}
		});

		// 投注列表的初始化
		touzhuMatchList = (PullToRefreshExpandableListView) findViewById(R.id.epl_touzhu_match_list);
		mTouzhuMatchListAdapter = new TouzhuMatchListAdapter(this);
		touzhuMatchList.setAdapter(mTouzhuMatchListAdapter);
		touzhuMatchList.setOnRefreshListener(new TouzhuOnRefreshListener());
		touzhuMatchList.setOnGroupExpandListener(new TouzhuOnExpandListener());
		touzhuMatchList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				if (mTouzhuMatchListAdapter.getGroup(groupPosition).getState() == GroupState.normal) {
					getToMatchDetailActivity(mTouzhuMatchListAdapter.getChild(
							groupPosition, childPosition));
				}
				return true;
			}

		});
		// tv_bindmobile.setText(UserInfo.getUserInfo().getBindmobile());

		// tv_yuan= (TextView)findViewById(R.id.yuan);
		// btn_account_in.setEnabled(false);
		// btn_account_in.setTextColor(Color.GRAY);
	}

	/**
	 * @title getToMatchDetailActivity
	 * @description 跳到比赛详情界面
	 * @param child
	 */
	protected void getToMatchDetailActivity(MatchInfo matchInfo) {
		Intent intent = new Intent(this, MatchInfoAct.class);
		intent.putExtra(IntentKey.INTENT_KEY_LEAGUE_NAME,
				matchInfo.getLeagueName());
		intent.putExtra(IntentKey.INTENT_KEY_MATCH_ID, matchInfo.getMatchId());
		intent.putExtra(IntentKey.INTENT_KEY_LEAGUE_ROUND, matchInfo.getRound());
		intent.putExtra(IntentKey.INTENT_KEY_STAGE, matchInfo.getStage());
		intent.putExtra(IntentKey.INTENT_KEY_HOST_NUMBER,
				matchInfo.getHostNumber());
		intent.putExtra(IntentKey.INTENT_KEY_GUEST_NUMBER,
				matchInfo.getGuestNumber());
		startActivity(intent);
	}

	/**
	 * @title getToMatchDetailActivity
	 * @description 跳到比赛详情界面
	 * @param child
	 */
	protected void getToMatchDetailActivity(AttentionGameInfo attentionGameInfo) {
		Intent intent = new Intent(this, MatchInfoAct.class);
		intent.putExtra(IntentKey.INTENT_KEY_LEAGUE_NAME,
				attentionGameInfo.getLeagueName());
		intent.putExtra(IntentKey.INTENT_KEY_MATCH_ID,
				attentionGameInfo.getMatchid());
		intent.putExtra(IntentKey.INTENT_KEY_LEAGUE_ROUND,
				attentionGameInfo.getRound());
		intent.putExtra(IntentKey.INTENT_KEY_STAGE,
				attentionGameInfo.getStage());
		intent.putExtra(IntentKey.INTENT_KEY_HOST_NUMBER,
				attentionGameInfo.getHomeNumber());
		intent.putExtra(IntentKey.INTENT_KEY_GUEST_NUMBER,
				attentionGameInfo.getAwayNumber());
		startActivity(intent);

	}

	private void initListener() {

		btn_betting_record_in.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(LoggedinAct.this,
						LotteryRecordAgp.class));
			}
		});
		btn_bingding_bank_card_in.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				// TODO Auto-generated method stub
				checkcardcommunicater = new CheckCardCommunicater(
						check_card_handler);
				checkcardcommunicater.startCommunicate();
				progressDialog.show();
			}
		});

		btn_change_password_in.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				startActivity(new Intent().setClass(LoggedinAct.this,
						PasswordModifyAct.class));
			}
		});
		btn_recharge_in.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				startActivity(new Intent(LoggedinAct.this,
						RechargeMenuPage.class));

			}
		});
		btn_withdraw_deposit_in.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				checkcardcommunicater = new CheckCardCommunicater(
						check_card_handler_withdrawal);
				checkcardcommunicater.startCommunicate();
				progressDialog.show();

				// TODO Auto-generated method stub

			}
		});
	}

	private void initHandler() {

		refreshHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					progressDialog.cancel();

					tv_return_money_in.setText(UserInfo.getUserInfo()
							.getMoney());
					final String bindPhonenew = UserInfo.getUserInfo()
							.getBindmobile();
					// 判断是否绑定了手机
					if (TextUtils.isDigitsOnly(bindPhonenew)) {
						StringBuilder strShowNum = new StringBuilder();
						String[] strMobileNum = bindPhonenew.split("|");
						for (int i = 0; i < strMobileNum.length; i++) {
							if (i > 3 && i < strMobileNum.length - 4) {
								strShowNum.append("*");
							} else {
								strShowNum.append(strMobileNum[i]);
							}
						}
						tv_bindmobile.setText(strShowNum.toString());
						// 显示修改手机号码

					} else {
						// 否则显示绑定手机
						tv_bindmobile.setText(bindPhonenew);

					}
					Toast.makeText(getParent(), "个人信息已更新", 500).show();
					break;
				case Config.COMMUNICATER_FAIL:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// checkcardcommunicater.getServerMsg(), false);
					Toast.makeText(getParent(),
							loggedinrefreshCommunicater.getServerMsg(), 500)
							.show();

					break;
				case Config.COMMUNICATER_EXCEPTION:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// Language.NERWORK_ABORT, false);
					Toast.makeText(getParent(), Language.NERWORK_ABORT, 500)
							.show();
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());

					break;
				}
			}
		};

		check_card_handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					progressDialog.cancel();
					if (checkcardcommunicater.getIsbind().equals("1")) {
						Intent intent = new Intent(LoggedinAct.this,
								BankCardBindingAct.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(LoggedinAct.this,
								RechargeUninUnbinding.class);
						startActivity(intent);

					}
					break;
				case Config.COMMUNICATER_FAIL:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// checkcardcommunicater.getServerMsg(), false);
					Toast.makeText(getParent(),
							checkcardcommunicater.getServerMsg(), 500).show();

					break;
				case Config.COMMUNICATER_EXCEPTION:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// Language.NERWORK_ABORT, false);
					Toast.makeText(getParent(), Language.NERWORK_ABORT, 500)
							.show();
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());

					break;
				}
			}
		};

		check_card_handler_withdrawal = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					progressDialog.cancel();
					if (checkcardcommunicater.getIsbind().equals("1")) {
						Intent intent = new Intent(LoggedinAct.this,
								WithdrawalAct.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(LoggedinAct.this,
								RechargeUninUnbinding.class);
						startActivity(intent);

					}
					break;
				case Config.COMMUNICATER_FAIL:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// checkcardcommunicater.getServerMsg(), false);
					Toast.makeText(getParent(),
							checkcardcommunicater.getServerMsg(), 500).show();
					break;
				case Config.COMMUNICATER_EXCEPTION:
					progressDialog.cancel();
					// ViewerUtil.showTipDialog(getParent(),
					// Language.NERWORK_ABORT, false);
					Toast.makeText(getParent(), Language.NERWORK_ABORT, 500)
							.show();
					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());

					break;
				}
			}
		};
	}

	/**
	 * @title initCommunicater
	 * @description 初始化通信类
	 */
	private void initCommunicater() {
		mAttentionMatchDoneListCommunicater = new AttentionMatchDoneListCommunicater(
				mHandler);
		mAttentionMatchFutureListCommunicater = new AttentionMatchFutureListCommunicater(
				mHandler);
		mAttentionMatchRightNowListCommunicater = new AttentionMatchRightNowListCommunicater(
				mHandler);

		mTouzhuMatchRightNowListCommunicater = new TouzhuMatchRightNowListCommunicater(
				mHandler);
		mTouzhuMatchFutureListCommunicater = new TouzhuMatchFutureListCommunicater(
				mHandler);
		mTouzhuMatchDoneListCommunicater = new TouzhuMatchDoneListCommunicater(
				mHandler);
	}

	public void CreatDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
		builder.setMessage(Language.EXIT);
		builder.setPositiveButton(Language.SURE,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						logout();
					}
				});
		builder.setNegativeButton(Language.CANCEL,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		builder.create().show();
	}

	private void logout() {
		new LoginOutComm(loginOutHandler).startCommunicate();
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setClass(LoggedinAct.this, HomeAct.class);
		HomeAct.flag = Language.FLAG_THREE;
		PersonalAct.flag = Language.FLAG_FIVE;
		startActivity(intent);
		clearsharedPreferences();
		LoggedinAct.this.finish();
		UserInfo.getUserInfo().setCk("");
		UserInfo.getUserInfo().setDefaultAccountTime(Language.DEFAULT_TIME);
		stopPushService();

		// ((ActivityGroup) (this.getParent().getParent()))
		// .getLocalActivityManager().removeAllActivities();
	}

	/**
	 * 停止接受push 的service
	 */
	private void stopPushService() {
		Intent i = new Intent();
		i.setClass(this, NotificationService.class);
		this.stopService(i);

	}

	private void clearsharedPreferences() {
		sharedPreferences_in = getSharedPreferences("cheetah",
				Context.MODE_PRIVATE);
		sharedPreferences_in.edit().clear().commit();
		EDebug.o("清除sharedpreferences ");
	}

	private void showQuitDialog() {
		// TODO Auto-generated method stub
		quitDialog = new Dialog(getParent(), R.style.dialog);
		quitDialog.getWindow().setContentView(R.layout.dialog_logout);

		// tvDialogMsg = (TextView) quitDialog.getWindow().findViewById(
		// R.id.dialogquit_tv_msg);
		// tvDialogMsg.setText(Language.MSG_QUITDIALOG);
		btnDialogcancel = (Button) quitDialog.getWindow().findViewById(
				R.id.dialogquit_btn_cancel);
		btnDialogcancel.setOnClickListener(LoggedinAct.this);
		btnDialogSubmit = (Button) quitDialog.getWindow().findViewById(
				R.id.dialogquit_btn_submit);
		btnDialogSubmit.setOnClickListener(this);

		quitDialog.show();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.dialogquit_btn_submit:
			// 退出前通信
			logout();
			quitDialog.dismiss();
			// finish();
			// android.os.Process.killProcess(android.os.Process.myPid());
			break;

		case R.id.dialogquit_btn_cancel:
			quitDialog.dismiss();
			break;
		case R.id.rbAttenMatch:
			btn_logout_in.setVisibility(View.GONE);
			btn_refresh.setVisibility(View.GONE);
			attentionMatchList.setVisibility(View.VISIBLE);
			touzhuMatchList.setVisibility(View.INVISIBLE);
			attentionTeamLayout.setVisibility(View.INVISIBLE);
			break;
		case R.id.rbAttenTeam:
			btn_refresh.setVisibility(View.GONE);
			btn_logout_in.setVisibility(View.VISIBLE);
			btn_logout_in.setId(100);
			btn_logout_in.setText(this.getText(R.string.add_tem));
			attentionTeamLayout.setVisibility(View.VISIBLE);
			attentionMatchList.setVisibility(View.INVISIBLE);
			touzhuMatchList.setVisibility(View.INVISIBLE);
			if (attenTeamIsFirstCall) {
				mAttenTeam = new AttenTeam(gainAtteTeamHandler, "zq", userName);
				elistView.loadData();
				attenTeamIsFirstCall = false;
			}

			break;

		case R.id.rbAlreadyBettingGame:
			btn_logout_in.setVisibility(View.INVISIBLE);
			btn_refresh.setVisibility(View.GONE);
			attentionMatchList.setVisibility(View.INVISIBLE);
			touzhuMatchList.setVisibility(View.VISIBLE);
			attentionTeamLayout.setVisibility(View.INVISIBLE);
			break;
		case R.id.btn_logout:
			showQuitDialog();
			break;
		case R.id.btn_refresh:
			refresh();
			break;
		case 100:
			Intent intent = new Intent(LoggedinAct.this, AddTeamAct.class);
			startActivity(intent);
		default:
			break;
		}

	}

	private void refresh() {
		loggedinrefreshCommunicater = new LoggedinrefreshCommunicater(
				refreshHandler);
		loggedinrefreshCommunicater.startCommunicate();
		progressDialog.show();
	}

	/**
	 * 账户的和关注的切换
	 */
	// @Override
	// public void onCheckedChanged(CompoundButton buttonView, boolean
	// isChecked) {
	// int viewId = buttonView.getId();
	// switch (viewId) {
	//
	// case R.id.tbAccountOrAttention:
	// if (isChecked) {
	// if (attentionTeamLayout.getVisibility() == View.VISIBLE) {
	// btn_logout_in.setVisibility(View.VISIBLE);
	// btn_logout_in.setId(100);
	// btn_logout_in.setText(this.getText(R.string.add_tem));
	// btn_refresh.setVisibility(View.GONE);
	// } else {
	// btn_logout_in.setVisibility(View.INVISIBLE);
	// btn_refresh.setVisibility(View.GONE);
	// }
	//
	// svPersonalContainer.setVisibility(View.GONE);
	// rlyAtten.setVisibility(View.VISIBLE);
	//
	// } else {
	// btn_logout_in.setVisibility(View.VISIBLE);
	// btn_logout_in.setId(R.id.btn_logout);
	// btn_logout_in.setText(getString(R.string.btn_logout));
	// svPersonalContainer.setVisibility(View.VISIBLE);
	// rlyAtten.setVisibility(View.GONE);
	// btn_refresh.setVisibility(View.VISIBLE);
	// }
	// break;
	// default:
	// break;
	// }
	//
	// }

	@Override
	protected void onResume() {
		final String bindPhone = UserInfo.getUserInfo().getBindmobile();
		// 判断是否绑定了手机
		if (TextUtils.isDigitsOnly(bindPhone)) {
			StringBuilder strShowNum = new StringBuilder();
			String[] strMobileNum = bindPhone.split("|");
			for (int i = 0; i < strMobileNum.length; i++) {
				if (i > 3 && i < strMobileNum.length - 4) {
					strShowNum.append("*");
				} else {
					strShowNum.append(strMobileNum[i]);
				}
			}
			tv_bindmobile.setText(strShowNum.toString());
			// 显示修改手机号码
			btn_bingding_mobile_phone_in.setVisibility(View.INVISIBLE);
			btnChangePhoneNumber.setVisibility(View.VISIBLE);
		} else {
			// 否则显示绑定手机
			tv_bindmobile.setText(bindPhone);
			btn_bingding_mobile_phone_in.setVisibility(View.VISIBLE);
			btnChangePhoneNumber.setVisibility(View.INVISIBLE);
		}

		tv_return_username_in.setText(UserInfo.getUserInfo().getUserName());
		tv_return_money_in.setText(UserInfo.getUserInfo().getMoney());

		boolean needUpdate = false;
		if (AttentionListManager.getInstance().isAttentionListChanged()
				|| AttentionListManager.getInstance().isAttentionListAdded()) {

			if (mAttentionMatchListAdapter.getGroupList()
					.get(AbsAttentionAdapter.POSITION_RIGHT_NOW).getState() != GroupState.uninitialized) {
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListRightNow(),
						AbsAttentionAdapter.POSITION_RIGHT_NOW);
				needUpdate = true;

			}

			if (mAttentionMatchListAdapter.getGroupList()
					.get(AbsAttentionAdapter.POSITION_FUTURE).getState() != GroupState.uninitialized) {
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListFuture(),
						AbsAttentionAdapter.POSITION_FUTURE);
				needUpdate = true;
			}

			if (mAttentionMatchListAdapter.getGroupList()
					.get(AbsAttentionAdapter.POSITION_DONE).getState() != GroupState.uninitialized) {
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListDone(),
						AbsAttentionAdapter.POSITION_DONE);
				needUpdate = true;
			}

			if (AttentionListManager.getInstance().isAttentionListAdded()) {
				attentionMatchList.loadData();
				needUpdate = true;
			}

			if (needUpdate) {
				mAttentionMatchListAdapter.notifyDataSetChanged();
			}

			AttentionListManager.getInstance().setAttentionListChanged(false);
			AttentionListManager.getInstance().setAttentionListAdded(false);
		}
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public void requestAttentionMatchList() {

	}

	/**
	 * @title AttentionHandler
	 * @description 关注列表，投注列表使用的handler
	 * @author liugan
	 */
	class AttentionHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 获取已结束关注比赛列表成功
			case Config.GET_ATTENTION_MATCH_DONE_LIST_SUCCESS:
				// 更新对应的二级列表数据及一级列表状态
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListDone(),
						AbsAttentionAdapter.POSITION_DONE);
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_DONE).setRefreshing(false);
				mAttentionMatchListAdapter.notifyDataSetChanged();
				// 检查是否是由下拉刷新引起、并作相应处理
				checkForAttentionPullRefresh();
				break;
			// 获取失败
			case Config.GET_ATTENTION_MATCH_DONE_LIST_EXCEPTION:
			case Config.GET_ATTENTION_MATCH_DONE_LIST_FAIL:
				AttentionGroupInfo groupInfoDone = mAttentionMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_DONE);
				// 如果是第一次加载，则收起改列表
				if (groupInfoDone.getState() == GroupState.uninitialized) {
					attentionMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_DONE);
				}
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_DONE).setRefreshing(false);
				checkForAttentionPullRefresh();
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			case Config.GET_ATTENTION_MATCH_FUTURE_LIST_SUCCESS:
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListFuture(),
						AbsAttentionAdapter.POSITION_FUTURE);
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_FUTURE).setRefreshing(
						false);
				mAttentionMatchListAdapter.notifyDataSetChanged();
				checkForAttentionPullRefresh();
				break;
			case Config.GET_ATTENTION_MATCH_FUTURE_LIST_EXCEPTION:
			case Config.GET_ATTENTION_MATCH_FUTURE_LIST_FAIL:
				AttentionGroupInfo groupInfoFuture = mAttentionMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_FUTURE);
				if (groupInfoFuture.getState() == GroupState.uninitialized) {
					attentionMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_FUTURE);
				}
				checkForAttentionPullRefresh();
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_FUTURE).setRefreshing(
						false);
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			case Config.GET_ATTENTION_MATCH_RIGHT_NOW_LIST_SUCCESS:
				mAttentionMatchListAdapter.setChildList(AttentionListManager
						.getInstance().getAttentionListRightNow(),
						AbsAttentionAdapter.POSITION_RIGHT_NOW);
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_RIGHT_NOW).setRefreshing(
						false);
				mAttentionMatchListAdapter.notifyDataSetChanged();
				checkForAttentionPullRefresh();
				break;
			case Config.GET_ATTENTION_MATCH_RIGHT_NOW_LIST_EXCEPTION:
			case Config.GET_ATTENTION_MATCH_RIGHT_NOW_LIST_FAIL:
				AttentionGroupInfo groupInfoRightNow = mAttentionMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_RIGHT_NOW);
				if (groupInfoRightNow.getState() == GroupState.uninitialized) {
					attentionMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_RIGHT_NOW);
				}
				checkForAttentionPullRefresh();
				mAttentionMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_RIGHT_NOW).setRefreshing(
						false);
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			case Config.GET_TOUZHU_MATCH_DONE_LIST_SUCCESS:
				mTouzhuMatchListAdapter.setChildList(
						mTouzhuMatchRightNowListCommunicater.getMatchList(),
						AbsAttentionAdapter.POSITION_DONE);
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_DONE).setRefreshing(false);
				mTouzhuMatchListAdapter.notifyDataSetChanged();
				checkForTouzhuPullRefresh();
				break;
			case Config.GET_TOUZHU_MATCH_DONE_LIST_EXCEPTION:
			case Config.GET_TOUZHU_MATCH_DONE_LIST_FAIL:
				AttentionGroupInfo groupInfoTouzhuDone = mTouzhuMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_DONE);
				if (groupInfoTouzhuDone.getState() == GroupState.uninitialized) {
					touzhuMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_DONE);
				}
				checkForTouzhuPullRefresh();
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_DONE).setRefreshing(false);
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			case Config.GET_TOUZHU_MATCH_FUTURE_LIST_SUCCESS:
				mTouzhuMatchListAdapter.setChildList(
						mTouzhuMatchFutureListCommunicater.getMatchList(),
						AbsAttentionAdapter.POSITION_FUTURE);
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_FUTURE).setRefreshing(
						false);
				mTouzhuMatchListAdapter.notifyDataSetChanged();
				checkForTouzhuPullRefresh();
				break;
			case Config.GET_TOUZHU_MATCH_FUTURE_LIST_EXCEPTION:
			case Config.GET_TOUZHU_MATCH_FUTURE_LIST_FAIL:
				AttentionGroupInfo groupInfoTouzhuFuture = mTouzhuMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_FUTURE);
				if (groupInfoTouzhuFuture.getState() == GroupState.uninitialized) {
					touzhuMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_FUTURE);
				}
				checkForTouzhuPullRefresh();
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_FUTURE).setRefreshing(
						false);
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			case Config.GET_TOUZHU_MATCH_RIGHT_NOW_LIST_SUCCESS:
				mTouzhuMatchListAdapter.setChildList(
						mTouzhuMatchRightNowListCommunicater.getMatchList(),
						AbsAttentionAdapter.POSITION_RIGHT_NOW);
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_RIGHT_NOW).setRefreshing(
						false);
				mTouzhuMatchListAdapter.notifyDataSetChanged();
				checkForTouzhuPullRefresh();
				break;
			case Config.GET_TOUZHU_MATCH_RIGHT_NOW_LIST_EXCEPTION:
			case Config.GET_TOUZHU_MATCH_RIGHT_NOW_LIST_FAIL:
				AttentionGroupInfo groupInfoTouzhuRightNow = mTouzhuMatchListAdapter
						.getGroup(AbsAttentionAdapter.POSITION_RIGHT_NOW);
				if (groupInfoTouzhuRightNow.getState() == GroupState.uninitialized) {
					touzhuMatchList
							.collapseGroup(AbsAttentionAdapter.POSITION_RIGHT_NOW);
				}
				checkForTouzhuPullRefresh();
				mTouzhuMatchListAdapter.getGroup(
						AbsAttentionAdapter.POSITION_RIGHT_NOW).setRefreshing(
						false);
				Toast.makeText(getBaseContext(), Language.INTERNET_FAIL,
						Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}

	}

	/**
	 * @title checkForPullRefresh
	 * @description 检查关注列表是否正在下拉刷新
	 */
	private void checkForAttentionPullRefresh() {
		if (pullRefreshingAttention) {
			mAttentionRefreshCount--;
			if (mAttentionRefreshCount == 0) {
				attentionMatchList.onRefreshComplete();
			}
		}
	}

	/**
	 * @title checkForPullRefresh
	 * @description 检查投注列表是否正在下拉刷新
	 */
	private void checkForTouzhuPullRefresh() {
		if (pullRefreshingTouzhu) {
			mTouzhuRefreshCount--;
			if (mTouzhuRefreshCount == 0) {

				pullRefreshingTouzhu = false;
				touzhuMatchList.onRefreshComplete();
			}
		}
	}

	/**
	 * @title AttentionOnRefreshListener
	 * @description 关注列表的刷新操作
	 * @author liugan
	 */
	class AttentionOnRefreshListener implements OnRefreshListener {

		@Override
		public void onRefresh() {
			mAttentionRefreshCount = 0;
			pullRefreshingAttention = true;
			for (AttentionGroupInfo groupInfo : mAttentionMatchListAdapter
					.getGroupList()) {
				if (groupInfo.getState() != GroupState.uninitialized) {
					mAttentionRefreshCount++;
					switch (groupInfo.getPosition()) {
					case AbsAttentionAdapter.POSITION_RIGHT_NOW:
						mAttentionMatchRightNowListCommunicater
								.startCommunicate();
						break;
					case AbsAttentionAdapter.POSITION_FUTURE:
						mAttentionMatchFutureListCommunicater
								.startCommunicate();
						break;
					case AbsAttentionAdapter.POSITION_DONE:
						mAttentionMatchDoneListCommunicater.startCommunicate();
						break;
					default:
						break;
					}
				}
			}
			if (mAttentionRefreshCount == 0) {
				attentionMatchList.onRefreshComplete();
				pullRefreshingAttention = false;
			}
		}

	}

	/**
	 * @title AttentionOnExpandListener
	 * @description 关注列表的展开
	 * @author liugan
	 */
	class AttentionOnExpandListener implements OnGroupExpandListener {

		@Override
		public void onGroupExpand(int groupPosition) {

			final GroupState state = mAttentionMatchListAdapter.getGroupList()
					.get(groupPosition).getState();
			final boolean notRefreshing = !mAttentionMatchListAdapter
					.getGroupList().get(groupPosition).isRefreshing();
			if (state == GroupState.uninitialized && notRefreshing) {
				switch (groupPosition) {
				case AbsAttentionAdapter.POSITION_RIGHT_NOW:
					mAttentionMatchRightNowListCommunicater.startCommunicate();
					break;
				case AbsAttentionAdapter.POSITION_FUTURE:
					mAttentionMatchFutureListCommunicater.startCommunicate();
					break;
				case AbsAttentionAdapter.POSITION_DONE:
					mAttentionMatchDoneListCommunicater.startCommunicate();
					break;
				default:
					break;
				}
			}

			for (int i = 0; i < AbsAttentionAdapter.GROUP_COUNT; i++) {
				if (i != groupPosition
						&& attentionMatchList.isGroupExpanded(groupPosition)) {
					attentionMatchList.collapseGroup(i);
				}
			}

		}

	}

	/***
	 * @title TouzhuOnRefreshListener
	 * @description 投注列表的刷新操作
	 * @author liugan
	 */
	class TouzhuOnRefreshListener implements OnRefreshListener {

		@Override
		public void onRefresh() {
			mTouzhuRefreshCount = 0;
			pullRefreshingTouzhu = true;
			for (AttentionGroupInfo groupInfo : mTouzhuMatchListAdapter
					.getGroupList()) {
				if (groupInfo.getState() != GroupState.uninitialized) {
					mTouzhuRefreshCount++;
					switch (groupInfo.getPosition()) {
					case AbsAttentionAdapter.POSITION_RIGHT_NOW:
						mTouzhuMatchRightNowListCommunicater.startCommunicate();
						break;
					case AbsAttentionAdapter.POSITION_FUTURE:
						mTouzhuMatchFutureListCommunicater.startCommunicate();
						break;
					case AbsAttentionAdapter.POSITION_DONE:
						mTouzhuMatchDoneListCommunicater.startCommunicate();
						break;
					}
				}
			}
			if (mTouzhuRefreshCount == 0) {
				touzhuMatchList.onRefreshComplete();
				pullRefreshingTouzhu = false;
			}
		}

	}

	/**
	 * @title TouzhuOnExpandListener
	 * @description 投注列表展开操作
	 * @author liugan
	 */
	class TouzhuOnExpandListener implements OnGroupExpandListener {

		@Override
		public void onGroupExpand(int groupPosition) {

			for (int i = 0; i < AbsAttentionAdapter.GROUP_COUNT; i++) {
				if (i != groupPosition
						&& touzhuMatchList.isGroupExpanded(groupPosition)) {
					touzhuMatchList.collapseGroup(i);
				}
			}

			final GroupState state = mTouzhuMatchListAdapter.getGroupList()
					.get(groupPosition).getState();
			final boolean notRefreshing = !mTouzhuMatchListAdapter
					.getGroupList().get(groupPosition).isRefreshing();
			if (state == GroupState.uninitialized && notRefreshing) {
				mTouzhuMatchListAdapter.getGroup(groupPosition).setRefreshing(
						true);
				switch (groupPosition) {
				case AbsAttentionAdapter.POSITION_RIGHT_NOW:
					mTouzhuMatchRightNowListCommunicater.startCommunicate();
					break;
				case AbsAttentionAdapter.POSITION_FUTURE:
					mTouzhuMatchFutureListCommunicater.startCommunicate();
					break;
				case AbsAttentionAdapter.POSITION_DONE:
					mTouzhuMatchDoneListCommunicater.startCommunicate();
					break;
				default:
					break;
				}
			}
		}

	}

	class AttentionTeamOnRefreshListener implements OnRefreshListener {
		@Override
		public void onRefresh() {
			mAttenTeam = new AttenTeam(gainAtteTeamHandler, "zq", userName);
			mAttenTeam.startCommunicate();

		}
	}
}
